package com.example.file.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author ZhenWuWang
 */
public class FileUtil
{
    public static synchronized void writeFile(File outFile, byte[] data) {
        try {
            int len = data.length;
            int bufferLen = 512;
            int count = len / bufferLen;
            FileOutputStream fos = new FileOutputStream(outFile);
            for (int i = 0; i < count; i++) {
                fos.write(data, i * bufferLen,bufferLen);
            }
            if (len > count * bufferLen) {
                fos.write(data, count * bufferLen, len - count * bufferLen);
            }
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(String fileName, String content) {
        FileWriter writer = null;
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            writer = new FileWriter(fileName, true);
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
